<template>
  <div ref="scrollableDiv" class="scrollable-div" @scroll="checkScroll">
    <SchemaForm
        v-if="getProps.search"
        ref="queryFormRef"
        class="bg-white dark:bg-black mb-16px !pt-24px pr-24px"
        submit-on-reset
        v-bind="getFormProps"
        :table-instance="tableAction"
        @toggle-advanced="(e) => $emit('toggle-advanced', e)"
        @submit="handleSubmit"
    >
      <template v-for="item of getFormSlotKeys" #[replaceFormSlotKey(item)]="data">
        <slot :name="item" v-bind="data || {}"/>
      </template>
    </SchemaForm>
    <div class="bg-white dark:bg-black" v-if="!$isMobile">
      <ToolBar
          v-if="showToolBar"
          :export-file-name="exportFileName"
          :title="headerTitle"
          :title-tooltip="titleTooltip"
          :show-table-setting="showTableSetting"
      >
        <template v-for="name of Object.keys($slots)" #[name]="data">
          <slot :name="name" v-bind="data || {}"/>
        </template>
      </ToolBar>
      <!--     -->
      <SchemaForm

          ref="editTableFormRef"
          no-style
          :initial-values="editFormModel"
          :show-action-button-group="false"
          :show-advanced-button="false"
          @validate="handleEditFormValidate"
      >
        <Table
            ref="tableRef"
            v-bind="tableProps"
            :columns="innerColumns"
            :data-source="tableData"
            @change="handleTableChange"
        >
          <template v-for="(_, slotName) of $slots" #[slotName]="slotData" :key="slotName">
            <slot :name="slotName" v-bind="slotData"/>
          </template>
          <template #bodyCell="slotData">
            <slot name="bodyCell" v-bind="slotData"/>
          </template>
        </Table>

      </SchemaForm>


    </div>
    <mobile-card-table
        v-if="$isMobile"
        :columns="innerColumns"
        :dataSource="tableData"
        @change="handleTableChange">
    </mobile-card-table>
  </div>
</template>

<script lang="tsx" setup>
import {useSlots, ref, onMounted, onUnmounted, computed} from 'vue';
import {Table} from 'ant-design-vue';
import {default as MobileCardTable} from "@/components/core/mobile-card-table/index.vue"
import {
  useTableMethods,
  createTableContext,
  useExportData2Excel,
  useTableForm,
  useTableState,
  useColumns,
  useEditable,
} from './hooks';
import {ToolBar} from './components';
import {dynamicTableProps, dynamicTableEmits} from './dynamic-table';
import type {TableActionType} from './types';
import {SchemaForm} from '@/components/core/schema-form';

defineOptions({
  name: 'DynamicTable',
  inheritAttrs: false,
});

const props = defineProps(dynamicTableProps);
const emit = defineEmits(dynamicTableEmits);
const slots = useSlots();

// 表格内部状态
const tableState = useTableState({props, slots});
const {
  tableRef,
  tableData,
  queryFormRef,
  editTableFormRef,
  getProps,
  getBindValues,
  editFormModel,
  paginationRef,
} = tableState;
// 表格内部方法
const tableMethods = useTableMethods({state: tableState, props, emit});
const {setProps, fetchData,fetchData2, handleSubmit, reload, handleTableChange, handleEditFormValidate} =
    tableMethods;
// 控制编辑行
const editableHooks = useEditable({props, state: tableState});
/** 表格scroll */
const tableAction: TableActionType = {
  setProps,
  reload,
  fetchData,
  ...editableHooks,
};

// 表格列的配置描述
const {innerColumns} = useColumns({
  props,
  slots,
  state: tableState,
  methods: tableMethods,
  tableAction,
});
console.log(innerColumns)
// 搜索表单
const tableForm = useTableForm({
  tableState,
  tableMethods,
  slots,
});
const {getFormProps, replaceFormSlotKey, getFormSlotKeys} = tableForm;

// 表单导出
const exportData2ExcelHooks = useExportData2Excel({
  props,
  state: tableState,
  methods: tableMethods,
});

// 当前组件所有的状态和方法
const instance = {
  ...props,
  ...tableState,
  ...tableForm,
  ...tableMethods,
  ...editableHooks,
  ...exportData2ExcelHooks,
  emit,
};

createTableContext(instance);

fetchData();
// console.log(tableData);
defineExpose(instance);

const tableProps = computed(() => {
  const {getExpandOption} = tableMethods;
  return {
    ...getBindValues.value,
    ...getExpandOption.value,
  };
});

const scrollableDiv = ref(null);
// 检查是否滚动到底部的函数
const checkScroll = () => {
  if (scrollableDiv.value && /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    const {scrollTop, scrollHeight, clientHeight} = scrollableDiv.value;

    // 下面这个判断存在问题
    // 问题：当numPage的值大于1时，scrollHeight的值不会更新，导致scrollTop + clientHeight >= scrollHeight始终为true，导致无限循环
    if (scrollTop + clientHeight + 20 >= scrollHeight) {
      // 例如：加载更多内容
      fetchData2()
      // 滚动到底部了，执行你的操作
      console.log('滚动到底部了！');
    }
  }
};
// 组件挂载后添加滚动事件监听器
onMounted(() => {
  console.log(123123)
  scrollableDiv.value.addEventListener('scroll', checkScroll);
});
// 组件卸载前移除滚动事件监听器
onUnmounted(() => {
  console.log(123123)
  if (scrollableDiv.value) {
    scrollableDiv.value.removeEventListener('scroll', checkScroll);
  }
});
</script>

<style lang="less" scoped>
:deep(.ant-table-wrapper) {
  padding: 0 6px 6px;

  .ant-table {
    .ant-table-title {
      display: flex;
    }

    .ant-image:hover {
      cursor: zoom-in;
    }
  }
}

.actions > * {
  margin-right: 10px;
}

.scrollable-div {
  /* 设置高度和溢出属性以启用滚动 */
  height: 80vh; /* 示例高度 */
  overflow-y: auto;
  /* 其他样式... */
}

::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
</style>
